package com.chenyuxin.ilp.service.user.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chenyuxin.ilp.exception.BaseException;
import com.chenyuxin.ilp.mapper.file.FileFolderMapper;
import com.chenyuxin.ilp.mapper.file.FileFolderMistakeMapper;
import com.chenyuxin.ilp.mapper.user.UserMapper;

import com.chenyuxin.ilp.mapper.user.UserStatisticsMapper;
import com.chenyuxin.ilp.mapper.user.UserStorageMapper;
import com.chenyuxin.ilp.model.constant.NormalConstant;
import com.chenyuxin.ilp.model.constant.RedisConstant;
import com.chenyuxin.ilp.model.constant.UserSuccessConstant;
import com.chenyuxin.ilp.model.dto.user.RegisterFormDto;
import com.chenyuxin.ilp.model.entity.file.FileFolder;
import com.chenyuxin.ilp.model.entity.file.FileFolderMistake;
import com.chenyuxin.ilp.model.entity.user.User;
import com.chenyuxin.ilp.model.entity.user.UserStatistics;
import com.chenyuxin.ilp.model.entity.user.UserStorage;
import com.chenyuxin.ilp.model.enums.exception.ExceptionEnums;
import com.chenyuxin.ilp.model.enums.exception.UserExceptionEnums;
import com.chenyuxin.ilp.model.enums.db.user.UserStatus;
import com.chenyuxin.ilp.model.pojo.Result;
import com.chenyuxin.ilp.service.user.RegisterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;
@Slf4j
@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserStorageMapper userStorageMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserStatisticsMapper userStatisticsMapper;
    @Autowired
    private FileFolderMapper fileFolderMapper;
    @Autowired
    private FileFolderMistakeMapper fileFolderMistakeMapper;


    @Transactional
    @Override
    public Result register(RegisterFormDto registerFormDto) {
        // 检查用户是否存在
        String username = registerFormDto.getUsername();
        LambdaQueryWrapper<User> nameWrapper = new LambdaQueryWrapper<>();
        nameWrapper.eq(User::getUsername, username);
        User nameUser = userMapper.selectOne(nameWrapper);
        if(nameUser!=null){
            throw new BaseException(UserExceptionEnums.USERNAME_REGISTERED);
        }
        String phone = registerFormDto.getPhone();
        LambdaQueryWrapper<User> phoneWrapper = new LambdaQueryWrapper<>();
        phoneWrapper.eq(User::getPhone,phone);
        User phoneUser = userMapper.selectOne(phoneWrapper);
        if(phoneUser!=null){
            throw new BaseException(UserExceptionEnums.PHONE_REGISTERED);
        }
        // 检查验证码是否过期
        String code = stringRedisTemplate.opsForValue().get(RedisConstant.REGISTER_PHONE + phone);
        if(code==null){
            throw new BaseException(UserExceptionEnums.PHONE_CODE_EXPIRED);
        }
        // 初始化用户信息
        User user = new User();
        String userId = UUID.randomUUID().toString().replace("-","");
        user.setId(userId);
        user.setUsername(registerFormDto.getUsername());
        user.setPhone(registerFormDto.getPhone());
        user.setPassword(passwordEncoder.encode(registerFormDto.getPassword()));
        user.setImg(NormalConstant.USER_DEFAULT_IMAGE);
        user.setStatus(UserStatus.ENABLED.getCode());
        user.setCreateTime(LocalDateTime.now());
        int insert1 = userMapper.insert(user);
        UserStorage userStorage = new UserStorage();
        userStorage.setUsedSize(0.0);
        userStorage.setTotalSize(100.0);
        userStorage.setId(userId);
        userStorage.setUpdateTime(LocalDateTime.now());
        int insert2 = userStorageMapper.insert(userStorage);
        // 初始化交互数据统计表
        UserStatistics userStatistics = new UserStatistics();
        userStatistics.setId(userId);
        userStatistics.setTotalLike(0L);
        userStatistics.setOpenFileView(0L);
        int insert3 = userStatisticsMapper.insert(userStatistics);
        stringRedisTemplate.opsForValue().set("open:view:total:"+userId,String.valueOf(0));
        stringRedisTemplate.opsForValue().set("open:preview:total:"+userId,String.valueOf(0));
        stringRedisTemplate.opsForValue().set("open:download:total:"+userId,String.valueOf(0));
        // 初始化用户文件夹
        FileFolder fileFolder = new FileFolder();
        fileFolder.setUserId(userId);
        fileFolder.setLevel(0);
        fileFolder.setCreateTime(LocalDateTime.now());
        fileFolder.setIsShare(0);
        int insert4 = fileFolderMapper.insert(fileFolder);
        if(insert1!=1||insert2!=1||insert3!=1||insert4!=1){
            throw new BaseException(ExceptionEnums.SYSTEM_ERROR);
        }
        // 初识化一个错题文件夹
        FileFolderMistake fileFolderMistake = new FileFolderMistake();
        fileFolderMistake.setFolderName(username+"的错题文件夹");
        fileFolderMistake.setCreateTime(LocalDateTime.now());
        fileFolderMistake.setUserId(userId);
        fileFolderMistakeMapper.insert(fileFolderMistake);
        return Result.ok(UserSuccessConstant.REGISTER_SUCCESS,null);
    }

}
